﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSP.Bll.CommonBll;
using CSP.Bll.IObjectBlls;
using CSP.Dao.IObjectDaos.CSP;
using CSP.Dao.IObjectDaos.CSPBBS;
using CSP.Common.Factories;
using CSP.Dao;
using CSP.Model.CSPBBS;
using CSP.Model.CSP;
using System.Security.Cryptography;
using CSP.Common.Tools;
using CSP.Model.CSPEnum;
using CSP.Bll.DTO.UserInfo;

namespace CSP.Bll.ObjectBlls
{
    public class UserInfoBll : CSPCommonBll, IUserInfoBll
    {
        private IUserBasicDao _userBasicDao;

        private IMemberDao _memberDao;

        private IMemberProfileDao _memberProfileDao;

        private ICommonMemberDao _commonMemberDao;

        private IDengLuBindInfoDao _dengLuBindInfoDao;

        /// <summary>
        /// 工厂Dao 工厂对象
        /// </summary>
        private CSPDaoFactory _factory;

        public UserInfoBll()
        {
            _factory = CSPDaoFactory.GetInstance();
            _cacheProvider = CachedProviderFactory.GetMemCachedProvider();
            _userBasicDao = _factory.GetUserBasicDao();
            _memberDao = _factory.GetMemberDao();
            _commonMemberDao = _factory.GetCommonMemberDao();
            _memberProfileDao = _factory.GetMemberProfileDao();
            _dengLuBindInfoDao = _factory.GetDengLuBindInfoDao();
        }

        public void AddUserInfo(Member member)
        {
            if (member == null)
            {
                throw new Exception("member Can't be null.");
            }
            member = GetMemberByReqeustMember(member);
            _memberDao.Add(member);

            Member temMember = _memberDao.GetInfoByUserName(member.UserName);
            member.Id = temMember.Id;

            CommonMember commonMember = GetCommonMemberByRequestMember(temMember);
            _commonMemberDao.Add(commonMember);
            member.CommonMember = commonMember;

            if (member.UserBasic != null)
            {
                _userBasicDao.Add(member.UserBasic);
            }
        }

        /// <summary>
        /// (普通登陆)获取Member
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <param name="loginType"></param>
        /// <returns></returns>
        public Model.CSPBBS.Member GetUser(string userName, string pwd)
        {
            Member member = _memberDao.GetInfoByUserName(userName);
            bool checkValue = CheckUserByMemberAndPassWord(member, pwd);
            if (!checkValue)
            {
                return null;
            }

            member = GetUser(userName, true);

            //如果不存在UserBasic那么将插入一个
            if (member.UserBasic == null)
            {
                UserBasic userBasic = GetUserBasicByRequestMember(member);
                _userBasicDao.Add(userBasic);
                member.UserBasic = userBasic;
            }
            return member;
        }

        /// <summary>
        /// （单点登陆）获取Member
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public Member GetUser(int uid, string pwd)
        {
            CommonMember commonMember = _commonMemberDao.GetDataById(uid);
            bool checkValue = CheckUserByCommonMemberAndPassWord(commonMember, pwd);
            if (!checkValue)
            {
                return null;
            }

            Member member = GetUser(uid, true);

            //如果不存在UserBasic那么将插入一个
            if (member.UserBasic == null)
            {
                UserBasic userBasic = GetUserBasicByRequestMember(member);
                _userBasicDao.Add(userBasic);
                member.UserBasic = userBasic;
            }
            return member;
        }

        public bool IsExsitByUserName(string userName)
        {
            return _memberDao.IsExsitByUserName(userName);
        }

        /// <summary>
        /// 获取用户基本信息
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="isLoadUserProfile">是否加载UserProfile信息,默认false</param>
        /// <returns></returns>
        public Model.CSPBBS.Member GetUser(string userName, bool isLoadUserProfile = false)
        {
            Member member = _memberDao.GetInfoByUserName(userName);

            if (member != null)
            {
                member.UserBasic = _userBasicDao.GetInfoByUserName(userName);
                member.CommonMember = _commonMemberDao.GetDataById(member.Id);
                
                //加载UserProfile
                if (isLoadUserProfile)
                {
                    member.MemberProfile = _memberProfileDao.GetDataById(member.Id);
                }
            }
           
            return member;
        }

        /// <summary>
        /// 根据用户Id获取基本信息
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="isLoadUserProfile"></param>
        /// <returns></returns>
        public Member GetUser(int uid, bool isLoadUserProfile = false)
        {
            Member member = _memberDao.GetDataById(uid);
            if (member != null)
            {
                member.UserBasic = _userBasicDao.GetInfoByUserName(member.UserName);
                member.CommonMember = _commonMemberDao.GetDataById(member.Id);
            }
            //加载UserProfile
            if (isLoadUserProfile)
            {
                member.MemberProfile = _memberProfileDao.GetDataById(member.Id);
            }
            return member;
        }

        public void AddUserBasic(UserBasic obj)
        {
            if (obj == null)
            {
                return;
            }
            _userBasicDao.Add(obj);

        }

        public void Update(Model.CSP.UserBasic obj)
        {
            _userBasicDao.Update(obj);
        }

        public void DeleteById(int id)
        {
            throw new NotImplementedException();
        }


        /// <summary>
        /// 获取用户资料
        /// </summary>
        /// <param name="uid">用户ID</param>
        /// <returns></returns>
        private MemberProfile GetUserProfile(int uid)
        {
            MemberProfile memberProfile = _memberProfileDao.GetDataById(uid);
            return memberProfile;
        }

        /// <summary>
        /// 根据请求的member 获取业务Member
        /// </summary>
        /// <param name="member"></param>
        /// <returns></returns>
        private Member GetMemberByReqeustMember(Member member)
        {
            member.salt = CommonTool.GenerateCode(6).ToLower();
            member.PassWord = UserNameEncryptByUserAndSalt(member.PassWord, member.salt);
            member.RegDate = DateTime.Now;
            member.LastLoginTime = DateTime.Now;
            member.MyId = string.IsNullOrWhiteSpace(member.MyId) ? "" : member.MyId;
            member.MyIdKey = string.IsNullOrWhiteSpace(member.MyIdKey) ? "" : member.MyIdKey;
            member.Secques = string.IsNullOrWhiteSpace(member.Secques) ? "" : member.Secques;
            //member.= string.IsNullOrWhiteSpace(member.MyIdKey) ? "" : member.MyIdKey;
            member.UserBasic = GetUserBasicByRequestMember(member);

            return member;
        }

        /// <summary>
        /// 根据请求的member 获取业务CommonMember
        /// </summary>
        /// <param name="member"></param>
        /// <returns></returns>
        private CommonMember GetCommonMemberByRequestMember(Member member)
        {
            CommonMember commonMember = new CommonMember();
            commonMember.Uid = member.Id;
            commonMember.Email = member.Email;
            commonMember.UserName = member.UserName;
            commonMember.PassWord = CommonTool.MD5(member.PassWord);
            commonMember.Status = 0;
            commonMember.EmailStatus = 0;
            commonMember.AvatarStatus = 0;
            commonMember.AdminId = 0;
            commonMember.Groupid = 10;
            commonMember.GroupeXpiry = 0;
            commonMember.ExtGroupIds = "";
            commonMember.Regdate = DateTime.Now;
            commonMember.Credits = 2;
            commonMember.Notifysound = 0;
            commonMember.TimeOffset = "9999";
            commonMember.Newpm = 0;
            commonMember.NewPrompt = 1;
            commonMember.Accessmasks = 0;
            commonMember.Allowadmincp = 0;
            commonMember.OnlyAcceptFriendpm = 0;
            commonMember.Conisbind = 0;
            return commonMember;
        }

        /// <summary>
        /// 根据请求的member 获取UserBasic
        /// </summary>
        /// <param name="member"></param>
        /// <returns></returns>
        private UserBasic GetUserBasicByRequestMember(Member member)
        {
            UserBasic userBasic = new UserBasic();
            userBasic.username = member.UserName;
            userBasic.EnterpriseAuthentication = (byte)Convert.ToInt32(AuthenticationStatus.Noting);
            userBasic.PersonalAuthentication = (byte)Convert.ToInt32(AuthenticationStatus.Noting);
            return userBasic;
        }

        /// <summary>
        /// 通过用户名和Salt
        /// </summary>
        /// <param name="passWord"></param>
        /// <param name="salt"></param>
        /// <returns></returns>
        private string UserNameEncryptByUserAndSalt(string passWord, string salt)
        {
            string result = CommonTool.MD5(CommonTool.MD5(passWord) + salt.ToLower());
            return result;
        }

        /// <summary>
        /// 普通登陆验证用户名密码
        /// </summary>
        /// <param name="member"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        private bool CheckUserByMemberAndPassWord(Member member, string pwd)
        {

            if (member == null)
            {
                return false;
            }

            return member.PassWord == UserNameEncryptByUserAndSalt(pwd, member.salt);
        }

        /// <summary>
        /// 单点登陆验证用户名密码
        /// </summary>
        /// <param name="commonMember"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        private bool CheckUserByCommonMemberAndPassWord(CommonMember commonMember, string pwd)
        {
            if (commonMember == null)
            {
                return false;
            }

            return commonMember.PassWord == pwd;
        }


        /// <summary>
        /// 根据用户名获取用户基本信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public UserBasic GetUserBasicByUser(string userName)
        {
            return _userBasicDao.GetInfoByUserName(userName);
        }


        public Member OtherLogin(UserLoginType userLoginType, string otherIdentity,string accessToken="")
        {
            Member result = null;
            DengLuBindInfo dengLuBindInfo=null;
            if (otherIdentity != null)
            {
                dengLuBindInfo = _dengLuBindInfoDao.GetDataByOtherIdenty(otherIdentity, userLoginType);
            }


            if (dengLuBindInfo != null)
            {
                if (!string.IsNullOrWhiteSpace(accessToken) && accessToken!=dengLuBindInfo.AccessToken)
                {
                    dengLuBindInfo.AccessToken = accessToken;
                    _dengLuBindInfoDao.Update(dengLuBindInfo);
                }
                result = GetUser(dengLuBindInfo.Uid, true);
            }

            return result;
        }

        /// <summary>
        /// 根据用户名和邮件第三方注册
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="email"></param>
        /// <param name="userLoginType"></param>
        /// <returns></returns>
        public Member OtherRegister(OtherRegisterDTO otherRegisterDTO)
        {
            Member member = new Member();
            member.UserName = otherRegisterDTO.UserName;
            member.PassWord = CommonTool.RandomString(6);
            member.Email = otherRegisterDTO.Email;
            //member.Salt = this.Txt_UserName.Value.Trim();
            member.LastLoginIp = 0;
            member.Regip =otherRegisterDTO.IP;
            AddUserInfo(member);
            
            //登陆绑定信息
            DengLuBindInfo dengLuBindInfo = new DengLuBindInfo();
            dengLuBindInfo.OtherIdenty = otherRegisterDTO.OtherIdentity;
            dengLuBindInfo.Uid = member.Id;
            dengLuBindInfo.MediaUserID = member.Id;
            dengLuBindInfo.CreateTime = member.RegDate;
            dengLuBindInfo.OtherIdenty = otherRegisterDTO.OtherIdentity;
            dengLuBindInfo.ScreenName = otherRegisterDTO.Screen_Name;
            dengLuBindInfo.Extendfield2 = "";
            dengLuBindInfo.Extendfield4 = "";
            dengLuBindInfo.MediaID = Convert.ToInt32(otherRegisterDTO.UserLoginType);
            dengLuBindInfo.AccessToken = otherRegisterDTO.Token;
            _dengLuBindInfoDao.Add(dengLuBindInfo);
            return member;
        }
    }
}
